//
//  PayHistoryAlertView.m
//  Wallets Manager
//
//  Created by MAC on 11/9/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "PayHistoryAlertView.h"

@interface PayHistoryAlertView ()

@end

@implementation PayHistoryAlertView
@synthesize inputTextField;
@synthesize cancelButton;
@synthesize payAllButton;
@synthesize addButton;
@synthesize payType = _payType;
@synthesize currentLoan;
@synthesize currentDebt;
@synthesize completedLabel;
@synthesize targetLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.payType = 0;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (_payType == 1) {
        [self.addButton setTitle:@"Add to Loan History" forState:UIControlStateNormal];
        self.targetLabel.text = [currentLoan.l_amount stringValue];
        NSMutableArray *historyLoanArray = [NSMutableArray arrayWithArray:[DataBaseAccess getAllLoanHistoryInLoan:currentLoan]];
        NSLog(@"History count: %d", [historyLoanArray count]);
        double completed = 0;
        for (LoanHistory *item in historyLoanArray) {
            completed += [item.lh_amount doubleValue];
        }
        self.completedLabel.text = [NSString stringWithFormat:@"%0.0f", completed];
    } else if (_payType == 2) {
        [self.addButton setTitle:@"Add to Debt History" forState:UIControlStateNormal];
        self.targetLabel.text = [currentDebt.d_amount stringValue];
        NSMutableArray *historyDebtArray = [NSMutableArray arrayWithArray:[DataBaseAccess getAllDebtHistoryInDebt:currentDebt]];
        NSLog(@"History count: %d", [historyDebtArray count]);
        double completed = 0;
        for (DebtHistory *item in historyDebtArray) {
            completed += [item.dh_amount doubleValue];
        }
        self.completedLabel.text = [NSString stringWithFormat:@"%0.0f", completed];
    }
    
    NSCalendar *cal = [NSCalendar currentCalendar];
    
    NSDate *date = [NSDate date];
    NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                     fromDate:date];
    [comps setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    today = [cal dateFromComponents:comps];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)cancelButtonPressed:(id)sender {
    [self.view removeFromSuperview];
}

- (IBAction)payAllButtonPressed:(id)sender {
    double input = [self.targetLabel.text doubleValue] - [self.completedLabel.text doubleValue];
    [self.inputTextField setText:[NSString stringWithFormat:@"%f", input]];
    [self.addButton sendActionsForControlEvents:UIControlEventTouchUpInside];
}

- (IBAction)addButtonPressed:(id)sender {
    folyAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    double walletBalance = [delegate.currentWallet.w_balance doubleValue];

    NSDate *now = [NSDate date];
    NSLog(@"KODAK | PAY TYPE: %d", self.payType);
    double inputValue = [inputTextField.text doubleValue];
    NSLog(@"%f", [self.completedLabel.text doubleValue]);
    if (_payType == 1) {
        //Add Loan History
        if (inputValue >  [currentLoan.l_amount doubleValue] - [self.completedLabel.text doubleValue]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Invalid input!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [self.inputTextField setText:nil];
            [self.inputTextField resignFirstResponder];
        } else if (inputValue <= 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Invalid input!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [self.inputTextField setText:nil];
            [self.inputTextField resignFirstResponder];
        } else if (inputValue == [currentLoan.l_amount doubleValue] - [self.completedLabel.text doubleValue]) {
            currentLoan.l_finished = [NSNumber numberWithBool:TRUE];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loanCompleted" object:currentLoan.l_name];
            delegate.currentWallet.w_balance = [NSNumber numberWithDouble:(walletBalance + inputValue)];
            [DataBaseAccess saveData];
            [DataBaseAccess createLoanHistory:[inputTextField.text doubleValue] onDate:now inLoan:currentLoan];

            [[NSNotificationCenter defaultCenter] postNotificationName:@"addLoanDebtHistory_onSuccess" object:nil];
            [self.view removeFromSuperview];
        } else {
            delegate.currentWallet.w_balance = [NSNumber numberWithDouble:(walletBalance + inputValue)];
            [DataBaseAccess createLoanHistory:[inputTextField.text doubleValue] onDate:now inLoan:currentLoan];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"addLoanDebtHistory_onSuccess" object:nil];
            [self.view removeFromSuperview];
        }
    } else if (_payType == 2) {
        //Add Debt History
        if (inputValue > [currentDebt.d_amount doubleValue] - [self.completedLabel.text doubleValue]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Invalid input!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [self.inputTextField setText:nil];
            [self.inputTextField resignFirstResponder];
        } else if (inputValue <= 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Invalid input!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [self.inputTextField setText:nil];
            [self.inputTextField resignFirstResponder];
        } else if (inputValue == [currentDebt.d_amount doubleValue] - [self.completedLabel.text doubleValue]) {
            currentDebt.d_finished = [NSNumber numberWithBool:TRUE];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"debtCompleted" object:currentDebt.d_name];
            delegate.currentWallet.w_balance = [NSNumber numberWithDouble:(walletBalance - inputValue)];
            [DataBaseAccess saveData];
            [DataBaseAccess createDebtHistory:[inputTextField.text doubleValue] onDate:now inDebt:currentDebt];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"addLoanDebtHistory_onSuccess" object:nil];
            [self.view removeFromSuperview];
        } else {
            delegate.currentWallet.w_balance = [NSNumber numberWithDouble:(walletBalance - inputValue)];
            [DataBaseAccess createDebtHistory:[inputTextField.text doubleValue] onDate:now inDebt:currentDebt];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"addLoanDebtHistory_onSuccess" object:nil];
            [self.view removeFromSuperview];
        }
    }
}

@end
